package com.liyunc.demo.application.service;

import com.liyunc.demo.bundle.user.org.service.UserPersonalAccountService;
import com.liyunc.demo.comp.auth.AuthenticatedUser;
import com.liyunc.demo.comp.auth.Authenticator;
import lombok.RequiredArgsConstructor;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author liyuncong
 * @version 1.0
 * @file DbCheckAuthenticatorService.java
 * @brief DbCheckAuthenticatorService
 * @details DbCheckAuthenticatorService
 * @date 2022-03-31
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                        NAME               DESCRIPTION
 * 2022-03-31                  liyuncong          Created
 */
@Service
@RequiredArgsConstructor
public class DbCheckAuthenticatorService<T> implements Authenticator<T> {

    @Autowired
    private final UserPersonalAccountService accountService;

    @Override
    public AuthenticatedUser<T> authenticate(String username, String password) {
        if (Strings.isNotBlank(username) && Strings.isNotBlank(password)) {
            return accountService
                .authenticate(username, password)
                .map(item -> new AuthenticatedUser<T>(
                    item.getLoginUsername(),
                    item.getAlias(),
                    String.valueOf(item.getUserPersonalAccountId())
                ))
                .stream()
                .findFirst()
                .orElse(null);
        }
        return null;
    }
}
